package com.hbpu.usercenter.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbpu.usercenter.dto.UserDTO;
import com.hbpu.usercenter.pojo.User;
import com.hbpu.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {
    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;
    private final RedissonClient redissonClient;

    public PreCacheJob(UserService userService, RedisTemplate<String, Object> redisTemplate, RedissonClient redissonClient) {
        this.userService = userService;
        this.redisTemplate = redisTemplate;
        this.redissonClient = redissonClient;
    }

    @Scheduled(cron = "0 47 10 * * *")
    public void preCacheUser() {
        // 创建一个分布式锁并给他命名
        RLock lock = redissonClient.getLock("friend-match:precachejob:docache:lock");
        try {
            // 尝试获取锁，第一位表示等待时间，
            // 第二位表示锁的失效时间，当值为-1时，将会使用Redisson的看门狗机制，自动续期，
            // 第三位表示时间单位
            // 看门狗机制：当方法执行时，每隔十秒检查锁是否还由当前线程持有，如果有，那就续期到三十秒
            // 当使用debug模式打断点卡住时，Redisson会认为服务器宕机，将不会续期。
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                Thread.sleep(30000);
                Page<User> userPage = new Page<>(1, 20);
                Page<User> page = userService.page(userPage);
                if (page != null) {
                    List<UserDTO> usersFromMySQL = page.getRecords().stream().map(userService::getProcessedUser).toList();
                    String redisKey = String.format("friend-match:user:recommend:%s", 1L);
                    //获取操作Redis中<k,v>存储结构的对象
                    ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
                    stringObjectValueOperations.set(redisKey, usersFromMySQL,30, TimeUnit.MINUTES);
                }
            }
        } catch (InterruptedException e) {
            log.error("doPreCacheUser error", e);
        } finally {
            // 如果锁是当前线程的就释放
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }
}
